<template>
  <div class="goods-management">
    <!-- 操作栏 -->
    <div class="operation-bar">
      <el-input
        v-model="searchText"
        placeholder="搜索书籍ID/名称/分类"
        style="width: 360px"
        clearable
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>新增书籍
      </el-button>
    </div>

    <!-- 数据表格 -->
    <el-table 
      :data="filteredBooks" 
      border 
      style="width: 100%"
      header-row-class-name="table-header"
      stripe
      highlight-current-row
    >
      <el-table-column prop="bookId" label="书籍ID" width="130" sortable align="center" />
      <el-table-column prop="name" label="书籍名称" width="180" />
      <el-table-column prop="author" label="作者" width="120" />
      <el-table-column prop="category" label="分类" width="120">
        <template #default="{ row }">
          <el-tag effect="plain" :type="categoryTagType[row.category]">
            {{ row.category }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="price" label="价格" width="120" align="center">
        <template #default="{ row }">
          <span style="color: #2ecc71;">¥{{ row.price.toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="stockStatus" label="库存状态" width="140" align="center">
        <template #default="{ row }">
          <el-tag :type="stockTagType[row.stockStatus]" effect="light">
            {{ stockStatusMap[row.stockStatus] }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="publishDate" label="出版日期" width="140" sortable />
      <el-table-column prop="description" label="书籍简介" width="220">
        <template #default="{ row }">
          <div class="content-preview">{{ row.description }}</div>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="160" fixed="right" align="center">
        <template #default="{ row }">
          <el-button size="small" type="primary" plain @click="handleEdit(row)">编辑</el-button>
          <el-button
            size="small"
            type="danger"
            plain
            @click="handleDelete(row.bookId)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEditMode ? '编辑书籍信息' : '新增图书'"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
        label-position="left"
      >
        <el-form-item label="书籍ID" prop="bookId">
          <el-input 
            v-model="formData.bookId" 
            :disabled="isEditMode"
            placeholder="请输入书籍ID（如：BK2024001）"
          />
        </el-form-item>
        <el-form-item label="书籍名称" prop="name">
          <el-input 
            v-model="formData.name"
            placeholder="请输入书籍全称"
          />
        </el-form-item>
        <el-form-item label="作者" prop="author">
          <el-input 
            v-model="formData.author"
            placeholder="请输入作者"
          />
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-select 
            v-model="formData.category"
            placeholder="请选择分类"
            style="width: 100%"
          >
            <el-option
              v-for="item in categories"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input-number
            v-model="formData.price"
            :min="0"
            :step="1"
            controls-position="right"
            style="width: 100%"
            :precision="2"
            placeholder="请输入价格"
          >
            <template #prefix>¥</template>
          </el-input-number>
        </el-form-item>
        <el-form-item label="库存状态" prop="stockStatus">
          <el-select 
            v-model="formData.stockStatus"
            placeholder="请选择状态"
            style="width: 100%"
          >
            <el-option
              v-for="item in stockOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="出版日期" prop="publishDate">
          <el-date-picker
            v-model="formData.publishDate"
            type="date"
            placeholder="选择出版日期"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="书籍简介" prop="description">
          <el-input 
            type="textarea"
            v-model="formData.description" 
            rows="4"
            placeholder="请输入书籍简介"
            show-word-limit
            maxlength="200"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确认提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 分类配置
const categories = [
  '文学小说',
  '科学技术',
  '经济管理',
  '历史传记',
  '艺术设计',
  '教育学习'
]

// 库存状态配置
const stockOptions = [
  { value: 0, label: '库存充足' },
  { value: 1, label: '库存紧张' },
  { value: 2, label: '暂时缺货' }
]

// 标签样式映射
const categoryTagType = {
  '文学小说': 'info',
  '科学技术': 'warning',
  '经济管理': 'danger',
  '历史传记': 'success',
  '艺术设计': 'primary',
  '教育学习': ''
}

const stockTagType = {
  0: 'success',
  1: 'warning',
  2: 'danger'
}

const stockStatusMap = {
  0: '充足',
  1: '紧张',
  2: '缺货'
}

// 书籍数据（10条）
const booksList = ref([
  {
    bookId: 'BK2024001',
    name: '三体：全三册',
    author: '刘慈欣',
    category: '文学小说',
    price: 89.90,
    stockStatus: 0,
    publishDate: '2023-05-01',
    description: '亚洲首部获得雨果奖的科幻巨作，描绘人类文明与三体文明的星际交锋'
  },
  {
    bookId: 'BK2024002',
    name: 'Python编程从入门到实践',
    author: 'Eric Matthes',
    category: '科学技术',
    price: 99.00,
    stockStatus: 1,
    publishDate: '2024-01-15',
    description: '全球Python编程畅销书，包含大量实战案例和项目开发指导'
  },
  {
    bookId: 'BK2024003',
    name: '经济学原理',
    author: '曼昆',
    category: '经济管理',
    price: 128.00,
    stockStatus: 0,
    publishDate: '2022-09-10',
    description: '经典经济学教材，系统阐述微观与宏观经济学的核心理论'
  },
  {
    bookId: 'BK2024004',
    name: '中国历代政治得失',
    author: '钱穆',
    category: '历史传记',
    price: 58.00,
    stockStatus: 2,
    publishDate: '2024-03-22',
    description: '史学大家钱穆经典著作，剖析中国历代政治制度演变'
  },
  {
    bookId: 'BK2024005',
    name: '艺术的故事',
    author: 'E.H.贡布里希',
    category: '艺术设计',
    price: 298.00,
    stockStatus: 0,
    publishDate: '2023-11-05',
    description: '艺术史经典入门读物，完整讲述从洞窟壁画到现代艺术的发展历程'
  },
  {
    bookId: 'BK2024006',
    name: '深度学习',
    author: 'Ian Goodfellow',
    category: '科学技术',
    price: 168.00,
    stockStatus: 1,
    publishDate: '2024-02-18',
    description: '深度学习领域奠基性著作，涵盖数学基础与前沿算法'
  },
  {
    bookId: 'BK2024007',
    name: '活着',
    author: '余华',
    category: '文学小说',
    price: 39.80,
    stockStatus: 0,
    publishDate: '2024-04-10',
    description: '当代文学经典，讲述普通人在历史洪流中的生存哲学'
  },
  {
    bookId: 'BK2024008',
    name: '原则',
    author: '瑞·达利欧',
    category: '经济管理',
    price: 89.00,
    stockStatus: 0,
    publishDate: '2023-08-25',
    description: '桥水基金创始人分享生活与工作的基本原则'
  },
  {
    bookId: 'BK2024009',
    name: '人类简史',
    author: '尤瓦尔·赫拉利',
    category: '历史传记',
    price: 68.00,
    stockStatus: 2,
    publishDate: '2024-05-12',
    description: '全球畅销书，宏观视角解读人类文明发展历程'
  },
  {
    bookId: 'BK2024010',
    name: '设计中的设计',
    author: '原研哉',
    category: '艺术设计',
    price: 79.90,
    stockStatus: 1,
    publishDate: '2023-12-30',
    description: '日本设计大师解析无印良品等经典案例的设计哲学'
  }
])

// 搜索功能
const searchText = ref('')
const filteredBooks = computed(() => {
  const search = searchText.value.toLowerCase()
  return booksList.value.filter(book => 
    book.bookId.toLowerCase().includes(search) ||
    book.name.toLowerCase().includes(search) ||
    book.author.toLowerCase().includes(search) ||
    book.category.toLowerCase().includes(search)
  )
})

// 对话框相关状态
const dialogVisible = ref(false)
const isEditMode = ref(false)
const formRef = ref(null)
const formData = reactive({
  bookId: '',
  name: '',
  author: '',
  category: '文学小说',
  price: 0,
  stockStatus: 0,
  publishDate: new Date().toISOString().split('T')[0],
  description: ''
})

// 表单验证规则
const formRules = {
  bookId: [
    { required: true, message: '书籍ID不能为空', trigger: 'blur' },
    { pattern: /^BK\d{7}$/, message: '格式：BK+7位数字', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入书籍名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在2到50个字符', trigger: 'blur' }
  ],
  price: [
    { required: true, message: '请输入价格', trigger: 'blur' },
    { type: 'number', min: 0, max: 9999, message: '价格范围0-9999元', trigger: 'blur' }
  ],
  category: { required: true, message: '请选择分类', trigger: 'change' }
}

// 处理添加
const handleAdd = () => {
  isEditMode.value = false
  resetForm()
  dialogVisible.value = true
}

// 处理编辑
const handleEdit = (row) => {
  isEditMode.value = true
  Object.assign(formData, { ...row })
  dialogVisible.value = true
}

// 处理删除
const handleDelete = (bookId) => {
  ElMessageBox.confirm('确定要删除该书籍？', '警告', {
    confirmButtonText: '确认删除',
    cancelButtonText: '取消',
    type: 'warning',
    confirmButtonClass: 'el-button--danger'
  }).then(() => {
    booksList.value = booksList.value.filter(b => b.bookId !== bookId)
    ElMessage.success('书籍删除成功')
  }).catch(() => {})
}

// 提交表单
const submitForm = async () => {
  await formRef.value.validate()
  if (isEditMode.value) {
    const index = booksList.value.findIndex(b => b.bookId === formData.bookId)
    booksList.value.splice(index, 1, { ...formData })
  } else {
    if (booksList.value.some(b => b.bookId === formData.bookId)) {
      return ElMessage.warning('书籍ID已存在')
    }
    booksList.value.push({ ...formData })
  }
  dialogVisible.value = false
  ElMessage.success(isEditMode.value ? '更新成功' : '新增成功')
}

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    bookId: '',
    name: '',
    author: '',
    category: '文学小说',
    price: 0,
    stockStatus: 0,
    publishDate: new Date().toISOString().split('T')[0],
    description: ''
  })
}
</script>

<style scoped lang="scss">
.goods-management {
  padding: 24px;
  background: #f8fafc;
  min-height: 100vh;

  .operation-bar {
    padding: 16px 24px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(44, 62, 80, 0.08);
    margin-bottom: 24px;
    display: flex;
    align-items: center;
    gap: 16px;
  }

  :deep(.table-header) th {
    background-color: #f8fafc !important;
    color: #64748b;
    font-weight: 600;
  }

  .el-table {
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(44, 62, 80, 0.08);
    
    .el-tag {
      font-size: 13px;
      padding: 0 8px;
      height: 26px;
      line-height: 24px;
    }
  }

  .content-preview {
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
    line-height: 1.5;
    color: #4a5568;
  }
}

.el-dialog {
  border-radius: 12px;
  
  .el-dialog__header {
    border-bottom: 1px solid #e2e8f0;
    margin: 0 24px;
    padding: 24px 0 16px;
  }
  
  .el-dialog__body {
    padding: 24px 32px;
  }
  
  .el-dialog__footer {
    border-top: 1px solid #e2e8f0;
    padding: 16px 24px;
  }
}

.el-form-item {
  margin-bottom: 20px;
}
</style>